package edu.neusoft.yiqibike.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import edu.neusoft.yiqibike.common.annotation.LoginUser;
import edu.neusoft.yiqibike.common.entity.mysql.Admin;
import edu.neusoft.yiqibike.common.entity.mysql.SystemDictionary;
import edu.neusoft.yiqibike.common.entity.vo.Response;
import edu.neusoft.yiqibike.common.entity.vo.SystemDictionaryVo;
import edu.neusoft.yiqibike.common.exception.ArgumentVerifyException;
import edu.neusoft.yiqibike.service.ISystemDictionaryService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * User：lyc
 * Date：2018-01-09
 * Time：21:37
 * Description：字典接口
 */
@RestController
@RequestMapping("/sys/dic")
public class SystemDictionaryController {
    @Autowired
    private ISystemDictionaryService dictionaryService;

    /**
     * 分页（排序）获取所有字典
     *
     * @param page
     * @return
     */
    @PostMapping("/list")
    public Response<Page<SystemDictionaryVo>> getList(@RequestBody Page<SystemDictionary> page) {
        return Response.success(dictionaryService.getList(page));
    }

    /**
     * 编辑/新增字典
     *
     * @param systemDictionary
     * @return
     */
    @PostMapping("/addOrEdit")
    public Response<String> addOrEditDictionary(@RequestBody SystemDictionary systemDictionary) {
        dictionaryService.addOrEditDictionary(systemDictionary);
        return Response.success();
    }

    /**
     * 获取所有父字典的id、code、value值
     *
     * @return
     */
    @GetMapping("/groups")
    public Response<List<Map<String, String>>> getAllGroups() {
        return Response.success(dictionaryService.getAllGroups());
    }

    /**
     * 恢复/级联禁用字典
     *
     * @param dictionary
     * @param admin
     * @return
     */
    @PutMapping("/limit")
    public Response<String> limit(@RequestBody SystemDictionary dictionary, @LoginUser Admin admin) {
        if (Objects.isNull(dictionary) || Objects.isNull(dictionary.getId()) || Objects.isNull(dictionary.getIsEnable())) {
            throw new ArgumentVerifyException("检测到非法参数");
        }
        dictionaryService.invertIsEnable(dictionary, admin);
        return Response.success();
    }

    /**
     * 根据指定ID级联删除字典
     *
     * @param ids
     * @return
     */
    @PostMapping("/delete")
    public Response<String> delete(@RequestBody List<String> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return Response.success("无字典需要删除");
        }
        dictionaryService.remove(ids);
        return Response.success();
    }

    /**
     * 根据父字典的code获取其下所有的子字典
     *
     * @param group
     * @return
     */
    @GetMapping("/group/{group}")
    public Response<List<SystemDictionary>> getDictionaryByGroup(@PathVariable String group) {
        if (StringUtils.isEmpty(group)) {
            throw new ArgumentVerifyException("字典类型不能为空");
        }
        List<SystemDictionary> dictionaries = dictionaryService.getDictionaryByGroup(group);
        return Response.success(dictionaries == null ? Lists.newArrayList() : dictionaries);
    }

    /**
     * 根据父字典ID分页获取父字典包括其下所有的子字典
     *
     * @param page
     * @return
     */
    @GetMapping("/groups/{id}")
    public Response<Page<SystemDictionaryVo>> getGroupsByCode(Page<SystemDictionary> page, @PathVariable String id) {
        return Response.success(dictionaryService.getGroupsByCode(page, id));
    }

    /**
     * 获取级别字典信息（包括“级别”和“级别标签”字典）
     *
     * @return
     */
    @GetMapping("/levels")
    public Response<List<Map<String, Object>>> getLevelList() {
        List<Map<String, Object>> data = new ArrayList<>();
        List<SystemDictionary> levels = dictionaryService.getDictionaryByGroup("levels");
        //按code(1-9)升序排序
        levels = levels.stream().sorted(Comparator.comparing(SystemDictionary::getCode,
                Comparator.comparing(Integer::valueOf, Integer::compare))).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(levels)) {
            return Response.success(data);
        }
        List<SystemDictionary> levelLabels = dictionaryService.getDictionaryByGroup("level_labels");
        //list->map
        Map<String, String> labels = levelLabels.stream().collect(Collectors.toMap(
                SystemDictionary::getCode, SystemDictionary::getValue));
        //三小级归为一大级
        for (int i = 0, j = 1; i < levels.size(); i += 3, j++) {
            List<SystemDictionary> options = levels.subList(i, i < levels.size() ? i + 3 : levels.size() - 1);
            data.add(ImmutableMap.of("label", labels.getOrDefault(String.valueOf(j), "未知级别"),
                    "options", options));
        }
        return Response.success(data);
    }
}
